import re, random
import time

from flask import Blueprint, jsonify

from db import db1
from utils.data import get_data

bp_login = Blueprint('logon', __name__)


# 发送验证码
@bp_login.route('/sendSms', methods=['POST'])
def sendSms():
    # 获取手机号
    data = get_data()
    try:
        mobile = data['mobile']
    except:
        return jsonify({"code": 10011, 'mes': '不能为空'})

    # 验证手机号是否合法
    res = re.match('^1[3-9]\d{9}$', mobile)
    if not res:
        return jsonify({"code": 10010, 'mes': '手机号不合法'})
    # 检查上次发送是否超过一分钟，1分钟内不能发
    sql = "select stime from trecord where mobile='%s' order by id desc limit 1" % (str(mobile))
    record = db1.find(sql)
    if record:
        # 判断时间是否在一分钟以内
        seconds = int(time.time()) - int(record['stime'])
        if seconds < 60:
            return jsonify({"code": 10012, "mes": '一分钟内不能重复发送'})
    # 生成验证码，发送
    code = random.randint(1000, 9999)
    # 当发送成功写入记录表
    sql2 = "insert into trecord(mobile,code,stime) values('%s',%d,%d)" % (str(mobile), code, int(time.time()))
    db1.insert(sql2)
    return jsonify({"code": 200, 'mes': '发送成功'})


@bp_login.route('/tlogin', methods=['POST'])
def tlogin():
    # 获取手机号验证码
    data = get_data()
    # 通过手机号去记录中表查询，查最近的一条
    sql = "select code,stime from trecord where mobile='%s' order by id desc limit 0,1" % (data['mobile'])
    res = db1.find(sql)
    # 验证码过期时间验证
    if int(time.time()) - int(res['stime']) > 60:
        return jsonify({"code": 10020, 'mes': '验证码已经过期，重新发送'})
    # 验证是否相同

    if res['code'] == int(data['code']):
        # 用户表中查询手机号是否存在
        sql1 = "select id from tuser where mobile='%s'" % (data['mobile'])
        user = db1.find(sql1)
        # 存在返回登录成功userid
        if user:
            return jsonify({"code": 200, 'userid': user['id'], 'mes': '登录成功'})
        # 不存在添加新用户返回userid
        sql2 = "insert into tuser(mobile) values('%s')" % (data['mobile'])
        db1.insert(sql2)
        sql3 = "select id from tuser where mobile='%s'" % (data['mobile'])
        user3 = db1.find(sql3)
        return jsonify({"code": 200, 'userid': user3['id'], "meslist": '登陆成功'})
    else:
        return jsonify({"code": 10021, 'mes': '验证码输入错误'})
